<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="98px"
    >
      <!-- <el-form-item label="资料ID" prop="name">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入资料ID"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="资料名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入资料名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资料分类" prop="name">
        <el-select
          v-model="queryParams.category_id"
          placeholder="请选择资料分类"
          size="small"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option
            v-for="item in classifyList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          v-hasPermi="['business:material:list']"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button
          type="danger"
          size="mini"
          v-hasPermi="['business:material:add']"
          @click="handleAdd"
          >上传资料</el-button
        >
        <!-- <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button> -->
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="list" style="width: 100%">
      <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资料ID" align="center" prop="id" />
      <el-table-column label="资料名称" align="center" prop="name" />
      <el-table-column label="资料类型" align="center">
        <!-- //类型（1=文本，2=图片，3=链接，4=视频，5=小程序） type -->
        <template slot-scope="scope">
          <span v-if="scope.row.type == 1">文本</span>
          <span v-else-if="scope.row.type == 2">图片</span>
          <span v-else-if="scope.row.type == 3">链接</span>
          <span v-else-if="scope.row.type == 4">视频</span>
          <span v-else-if="scope.row.type == 5">小程序</span>
          <span v-else-if="scope.row.type == 6">视频号</span>
        </template>
      </el-table-column>
      <el-table-column
        label="资料描述"
        align="center"
        prop="desc"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="资料级别" align="center" prop="grade" />
      <el-table-column label="资料分类" align="center" prop="category_name" />
      <el-table-column label="更新时间" align="center" prop="update_time" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetail(scope.row)"
            v-hasPermi="['business:material:list']"
            >查看</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleEdit(scope.row)"
            v-hasPermi="['business:material:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleRemove(scope.row)"
            v-hasPermi="['business:material:remove']"
            >作废</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pageNum"
      :limit.sync="pageSize"
      @pagination="getList"
    />
    <!-- 添加分类 -->
    <el-dialog
      :title="form.id ? '修改资料' : '新增资料'"
      :visible.sync="dialogFormVisible"
      width="800px"
    >
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-row>
          <el-col :span="12">
            <el-form-item label="资料类型" prop="type" label-width="100px">
              <el-select v-model="form.type" placeholder="请选择资料类型">
                <el-option
                  v-for="item in types"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资料级别" prop="grade" label-width="100px">
              <el-select v-model="form.grade" placeholder="请选择资料级别">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资料名称" prop="name" label-width="100px">
              <el-input v-model="form.name" autocomplete="off"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="资料分类"
              prop="category_id"
              label-width="100px"
            >
              <el-select
                v-model="form.category_id"
                placeholder="请选择资料分类"
              >
                <el-option
                  v-for="item in classifyList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图" prop="cover_image" label-width="100px">
              <browserjs-upload @success="handleAvatarSuccessCover">
                <el-upload
                  class="avatar-uploader"
                  action="/admin-api/common/upload"
                  :show-file-list="false"
                  disabled
                >
                  <!-- 
                :on-success="handleAvatarSuccessCover"
                :before-upload="beforeAvatarUpload" -->
                  <img
                    v-if="form.cover_image"
                    :src="form.cover_image"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </browserjs-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- 类型（1=文本，2=图片，3=链接，4=视频） -->
            <!-- content 文本 -->
            <!-- link 链接 -->
            <!-- img_url 图片 -->
            <!-- video_url 视频地址 -->
            <el-form-item
              label="资料内容"
              v-if="form.type == 1"
              prop="content"
              label-width="100px"
            >
              <!-- <editor ref="content" v-model="form.content" :min-height="192" /> -->
              <el-input
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 1000 }"
                :maxlength="1000"
                v-model="form.content"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="图片内容"
              v-if="form.type == 2"
              prop="img_url"
              label-width="100px"
            >
              <!-- <editor ref="img_url" v-model="form.img_url" :min-height="192" /> -->
              <el-upload
                class="upload-demo"
                action="/admin-api/common/upload"
                :on-remove="handleRemoveImgs"
                :on-success="handleAvatarSuccessImgs"
                :file-list="fileList1"
                list-type="picture"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传jpg/png文件，且不超过50mb
                </div>
              </el-upload>
            </el-form-item>
            <el-form-item
              label="链接内容"
              v-if="form.type == 3"
              prop="link"
              label-width="100px"
            >
              <el-input v-model="form.link" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item
              label="视频内容"
              prop="video_url"
              v-if="form.type == 4"
              label-width="100px"
            >
              <browserjs-upload @success="handleVideoSuccess">
                <el-upload
                  class="avatar-uploader"
                  action="/admin-api/common/upload"
                  :show-file-list="false"
                  disabled
                >
                  <!-- :on-success="handleVideoSuccess"
                  :on-error="handleVideoError"
                  :before-upload="beforeVideoUpload" -->
                  <video v-if="form.video_url" controls class="avatar">
                    <source :src="form.video_url" type="video/mp4" />
                    您的浏览器不支持 HTML5 视频。
                  </video>
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </browserjs-upload>
            </el-form-item>
            <!-- <el-form-item
              label="资料内容"
              prop="video_url"
              label-width="100px"
              v-if="form.type == 4"
            >
              <el-upload
                class="avatar-uploader"
                action="/admin-api/common/upload"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :on-remove="handleRemove"
                :limit="1"
                :file-list="fileList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  只能上传视频文件，且不超过50mb
                </div>
              </el-upload>
            </el-form-item> -->
            <el-form-item
              label="小程序ID"
              v-if="form.type == 5"
              prop="applet_app_id"
              label-width="100px"
            >
              <el-input
                v-model="form.applet_app_id"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="小程序路径"
              v-if="form.type == 5"
              prop="applet_path"
              label-width="100px"
            >
              <el-input
                v-model="form.applet_path"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="视频号ID"
              v-if="form.type == 6"
              prop="applet_app_id"
              label-width="100px"
            >
              <el-input
                v-model="form.applet_app_id"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="视频feedId"
              v-if="form.type == 6"
              prop="applet_path"
              label-width="100px"
            >
              <el-input
                v-model="form.applet_path"
                autocomplete="off"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="资料描述" prop="desc" label-width="100px">
              <el-input
                type="textarea"
                v-model="form.desc"
                autocomplete="off"
                :autosize="{ minRows: 4, maxRows: 1000 }"
                :maxlength="200"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示/隐藏" label-width="100px">
              <el-radio-group v-model="form.show_flag">
                <el-radio :label="0">显示</el-radio>
                <el-radio :label="1">隐藏</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClassify('ruleForm')"
          >保 存</el-button
        >
      </div>
    </el-dialog>
    <!-- 查看 -->
    <el-dialog title="详情" :visible.sync="detailVisible" width="800px">
      <el-form :model="form">
        <el-row>
          <el-col :span="12">
            <el-form-item label="资料类型" prop="type" label-width="100px">
              <div>
                {{ types.find((item) => item.value == form.type).label }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资料级别" prop="grade" label-width="100px">
              <div>
                {{ options.find((item) => item.value == form.grade).label }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资料名称" prop="name" label-width="100px">
              <div>{{ form.name }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="资料分类"
              prop="category_id"
              label-width="100px"
            >
              <div>
                {{ form.category_name }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面图" prop="cover_image" label-width="100px">
              <img
                v-if="form.cover_image"
                :src="form.cover_image"
                class="avatar"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <!-- 类型（1=文本，2=图片，3=链接，4=视频，5=小程序） -->
            <!-- content 文本 -->
            <!-- link 链接 -->
            <!-- img_url 图片 -->
            <!-- video_url 视频地址 -->
            <el-form-item label="资料内容">
              <div class="rui-editor-content">
                <div v-if="form.type == 1" v-html="form.content"></div>
                <div v-if="form.type == 2">
                  <img
                    :src="item"
                    v-for="item in form.img_url.split(',')"
                    :key="item"
                    style="display: block; width: 100%; height: auto"
                  />
                </div>
                <div v-if="form.type == 3" v-html="form.link"></div>
                <div v-if="form.type == 4">
                  <video controls class="avatar">
                    <source :src="form.video_url" type="video/mp4" />
                    您的浏览器不支持 HTML5 视频。
                  </video>
                </div>
                <div v-if="form.type == 5">
                  <div>小程序Id: {{ form.applet_app_id }}</div>
                  <div>小程序路径: {{ form.applet_path }}</div>
                </div>
                <div v-if="form.type == 6">
                  <div>视频号ID: {{ form.applet_app_id }}</div>
                  <div>视频feedId: {{ form.applet_path }}</div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="资料描述" prop="desc" label-width="100px">
              <div>{{ form.desc }}</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示/隐藏" label-width="100px">
              <div v-html="form.show_flag == 0 ? '显示' : '隐藏'"></div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="显示/隐藏" label-width="100px">
              <div v-html="form.show_flag == 0 ? '显示' : '隐藏'"></div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="checkOver">确 认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, add, remove, detail, edit, classify } from "@/api/material/list";
import Editor from "@/components/Editor";
import BrowserjsUpload from "./BrowserjsUpload.vue";
export default {
  name: "List",
  components: {
    Editor,
    BrowserjsUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      dialogFormVisible: false,
      // 详情
      detailVisible: false,
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      pageNum: 1,
      pageSize: 10,
      // 查询参数
      queryParams: {
        name: undefined,
        category_id: undefined,
      },
      classifyList: [],
      fileList: [],
      fileList1: [],
      // 类型（1=文本，2=图片，3=链接，4=视频，5=小程序）
      types: [
        { value: 1, label: "文本" },
        { value: 2, label: "图片" },
        { value: 3, label: "链接" },
        { value: 4, label: "视频" },
        { value: 5, label: "小程序" },
        { value: 6, label: "视频号" },
      ],
      options: [
        { value: 1, label: "1 级" },
        { value: 2, label: "2 级" },
        { value: 3, label: "3 级" },
        { value: 4, label: "4 级" },
        { value: 5, label: "5 级" },
      ],
      form: {
        type: 1, //类型（1=文本，2=图片，3=链接，4=视频）
        category_id: "", //分类ID
        grade: 1, //会员等级（从1开始升高）
        name: "", //教程标题
        cover_image: "", //教程封面图
        content: "", //教程富文本内容
        link: "", //链接地址
        img_url: "", //图片地址（多个用逗号,隔开）
        video_url: "", //视频地址
        sort: 0, //排序
        show_flag: 0, //显示/隐藏标志（0=显示，1=隐藏）
        desc: "", //描述
        applet_app_id: "", //小程序ID
        applet_path: "", //小程序路径
      },
      rules: {
        type: [{ required: true, message: "请选择资料类型", trigger: "blur" }],
        grade: [{ required: true, message: "请选择资料级别", trigger: "blur" }],
        name: [{ required: true, message: "请输入资料名称", trigger: "blur" }],
        category_id: [
          { required: true, message: "请选择资料分类", trigger: "blur" },
        ],
        cover_image: [
          { required: true, message: "请上传资料封面图", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入资料内容", trigger: "blur" },
        ],
        img_url: [
          { required: false, message: "请输入资料内容", trigger: "blur" },
        ],
        link: [{ required: false, message: "请输入资料内容", trigger: "blur" }],
        video_url: [
          { required: false, message: "请上传资料内容", trigger: "blur" },
        ],
        applet_app_id: [
          { required: false, message: "请输入小程序ID", trigger: "blur" },
        ],
        applet_path: [
          { required: false, message: "请输入小程序路径", trigger: "blur" },
        ],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        desc: [{ required: true, message: "请输入资料描述", trigger: "blur" }],
      },
    };
  },
  watch: {
    "form.type": function (val) {
      const resetRuleNames = {
        1: "content",
        2: "img_url",
        3: "link",
        4: "video_url",
        5: ["applet_app_id", "applet_path"],
        6: ["applet_app_id", "applet_path"],
      }[`${val}`];
      this.resetRules(resetRuleNames, val);
    },
  },
  created() {
    this.getList();
    this.getClassify();
  },
  methods: {
    resetRules(types, val) {
      const resetRuleNames = {
        content: "请输入资料内容",
        img_url: "请输入资料内容",
        link: "请输入资料内容",
        video_url: "请输入资料内容",
        applet_app_id: val == 6 ? "请输入视频号 ID" : "请输入小程序 ID",
        applet_path: val == 6 ? "请输入视频 feedId" : "请输入小程序路径",
      };
      for (let key in resetRuleNames) {
        this.rules[key] = [
          {
            required: types.includes(key),
            message: resetRuleNames[key],
            trigger: "blur",
          },
        ];
      }
    },
    // 新增
    handleAdd() {
      this.dialogFormVisible = true;
      this.fileList = [];
      this.fileList1 = [];
      this.form = {
        type: 1, //类型（1=文本，2=图片，3=链接，4=视频）
        category_id: "", //分类ID
        grade: 1, //会员等级（从1开始升高）
        name: "", //教程标题
        cover_image: "", //教程封面图
        content: "", //教程富文本内容
        link: "", //链接地址
        img_url: "", //图片地址（多个用逗号,隔开）
        video_url: "", //视频地址
        sort: 0, //排序
        show_flag: 0, //显示/隐藏标志（0=显示，1=隐藏）
        desc: "", //描述
        applet_app_id: "", //小程序ID
        applet_path: "", //小程序路径
      };
    },
    handleAvatarSuccess(file, fileList) {
      this.fileList = [{ url: file.url, name: file.fileName }];
      this.form.video_url = file.url;
    },
    handleVideoSuccess(url) {
      console.log("handleVideoSuccess", url);
      this.form.video_url = url;
    },
    handleVideoError(err, file, fileList) {
      console.log(err);
      this.msgSuccess("上传失败！");
    },
    handleAvatarSuccessImgs(file, fileList) {
      this.fileList1 = [
        ...this.fileList1,
        { url: file.url, name: file.fileName },
      ];
      this.form.img_url = this.fileList1.map((item) => item.url).join(",");
    },
    handleRemoveImgs(file, fileList) {
      console.log("handleRemoveImgs", file, fileList);
      this.fileList1 = fileList;
      this.form.img_url = this.fileList1.map((item) => item.url).join(",");
    },
    handleAvatarSuccessCover(url) {
      console.log("handleAvatarSuccessCover", url);
      this.form.cover_image = url;
    },
    beforeAvatarUpload() {},
    addClassify(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let method = this.form.id ? edit : add;
          method(this.form).then((response) => {
            this.dialogFormVisible = false;
            this.getList();
            this.msgSuccess(this.form.id ? "修改成功" : "新增成功");
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 查看
    handleDetail(row) {
      detail({ id: row.id }).then((response) => {
        this.detailVisible = true;
        this.form = response?.data;
        this.form.type = this.form.type - 0;
        this.form.grade = this.form.grade - 0;
        this.form.show_flag = this.form.show_flag - 0;
        this.form.category_name = this.classifyList.find(
          (item) => item.id == this.form.category_id
        ).name;
        console.log(this.form);
      });
    },
    checkOver() {
      this.detailVisible = false;
    },
    // 修改
    handleEdit(row) {
      detail({ id: row.id }).then((response) => {
        this.dialogFormVisible = true;
        this.form = response?.data;
        this.form.type = this.form.type - 0;
        this.form.grade = this.form.grade - 0;
        this.form.show_flag = this.form.show_flag - 0;
        if (this.form.type == 2) {
          this.fileList1 = this.form.img_url.split(",").map((item) => {
            return { url: item, name: item.split("/").pop() };
          });
        } else if (this.form.type == 4) {
          this.fileList = [
            {
              url: this.form.video_url,
              name: this.form.video_url.split("/").pop(),
            },
          ];
        }
      });
    },
    // 删除
    handleRemove(row) {
      this.$confirm("此操作将作废该资料, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return remove({ id: row.id });
        })
        .then(() => {
          this.getList();
          this.msgSuccess("作废成功！");
        });
    },
    /** 查询登录日志列表 */
    getList() {
      this.loading = true;
      console.log({
        ...this.queryParams,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      });
      list({
        ...this.queryParams,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((response) => {
        this.list = response?.data?.records;
        console.log(this.list);
        this.total = response?.data?.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    getClassify() {
      classify().then((response) => {
        this.classifyList = response.data;
      });
    },
  },
};
</script>
<style>
.rui-editor-content img {
  width: 100%;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
